package cn.lger.controller;

import cn.lger.dao.UserDao;
import cn.lger.entity.Role;
import cn.lger.entity.User;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * Code that Changed the World
 * Pro said
 *
 * 调用安全框架方法判断当前的用户角色是否能够访问
 * //@PreAuthorize("hasAnyAuthority('ADMIN')")
 * @author Pro
 * @date 2018-03-28
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserDao userDao;

    @GetMapping("/list")
    public String listUsers(Model model) {

        List<User> users = userDao.findAll();
        //将users添加到modelAndView中，Spring底层会将这个Object加入httpRequest中
        model.addAttribute("users", users);
        return "/user-list.btl";
    }

    @PostMapping("/save")
    @ResponseBody
    public User saveUser(User user) {
        if (user.getRole() == null)
            user.setRole(Role.STUDENT);
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        return userDao.save(user);
    }

    @PostMapping("/delete")
    @ResponseBody
    public String deleteUserById(Integer id) {
        if (id == null) {
            return "error";
        } else {
            userDao.deleteById(id);
            return "success";
        }
    }

}
